//
//  MusicControlIntents.swift
//  TimMusic
//
//  Created by nkl on 2024/10/21.
//

import AppIntents
import Foundation
import TSVideoKit
import UIKit

enum OptionType: String {
    case play
    case pause
    case playnext
    case playlast
}

@available(iOS 16, *)
struct MusicClickIntent: AudioPlaybackIntent {
    static var title: LocalizedStringResource = "MusicClickIntent"
    @Parameter(title: "urlString")
    var urlString: String?
    // 定义意图行为
    func perform() async throws -> some IntentResult {
        // 这里处理点击事件，比如更新数据或执行任务
        print("Widget clicked, intent executed")
        if let urlStr = urlString, let url = URL(string: urlStr) {
            let param = parameter(url: url, param: "option")
            switch param {
            case OptionType.play.rawValue:
                await TSVideoOperator.shared.playerController.player.play()
            case OptionType.playnext.rawValue:
                await TSVideoOperator.shared.playerController.playNext()
            case OptionType.playlast.rawValue:
                await TSVideoOperator.shared.playerController.playLast()
            case OptionType.pause.rawValue:
                await TSVideoOperator.shared.playerController.pause()
            default:
                break
            }
        }
        return .result()
    }
    

    public func parameter(url: URL, param: String) -> String {
        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true),
              let queryItems = components.queryItems else { return "" }
        let sss = queryItems.reduce(into: [String: String]()) { result, item in
            result[item.name] = item.value
        }
        if let value = sss[param] {
            return value
        }
        return ""
    }
}
